package userlogic

import (
	"context"

	"gitee.com/liuxuezhan/ar-platform/login-rpc/internal/dao/model"
	"gitee.com/liuxuezhan/ar-platform/login-rpc/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/login-rpc/login_rpc"
	config "gitee.com/liuxuezhan/ar-platform/login-rpc/pkg/code"

	"github.com/zeromicro/go-zero/core/logx"
)

type RetrieveLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRetrieveLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RetrieveLogic {
	return &RetrieveLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RetrieveLogic) Retrieve(in *login_rpc.RetrieveRequest) (*login_rpc.RetrieveResponse, error) {
	var commonResp login_rpc.CommonResp
	if in.Account == "" || in.Password == "" {
		commonResp.Code = config.ParameterError
		commonResp.Message = "account or password is empty"
		return &login_rpc.RetrieveResponse{CommonResp: &commonResp}, nil
	}

	var userId int64
	var err error
	if in.UserType == 1 {
		userId, _ = model.NewUserTotalModel(l.ctx, l.svcCtx.Db).GetUserByPhone(in.Account, in.PhoneCode)
	} else if in.UserType == 2 {
		userId, _ = model.NewUserTotalModel(l.ctx, l.svcCtx.Db).GetUserByEmail(in.Account)
	} else {
		commonResp.Code = config.ParameterError
		commonResp.Message = "unsupported user type"
		return &login_rpc.RetrieveResponse{CommonResp: &commonResp}, nil
	}

	if userId == 0 {
		commonResp.Code = config.ParameterError
		commonResp.Message = "no such user"
		return &login_rpc.RetrieveResponse{CommonResp: &commonResp}, nil
	}

	err = model.NewUserModel(l.ctx, l.svcCtx.Db).UpdateUserPassword(userId, HashPassword(in.Password))
	if err != nil {
		logx.Errorf("UpdateUserPassword req: %v error: %v", in, err)
		commonResp.Code = config.DBError
		commonResp.Message = "update user password failed"
		return &login_rpc.RetrieveResponse{CommonResp: &commonResp}, nil
	}

	return &login_rpc.RetrieveResponse{UserId: userId, CommonResp: &commonResp}, nil
}
